var express = require('express');
var query = require("../util/dbHelper.js");
var router = express.Router();

//减少数量
router.post("/add", (req, res, next) => {
    if(req.body.id){//加数量
        req.myPromise = query('UPDATE `dt_mi_cart` SET num = ? WHERE `id` = ?;', [req.body.num, req.body.id])//查询数据库id相同的数据把num设置
            .then(result => {
                if(result.affectedRows === 1){//返回的数据库受影响的行
                    return {state: 200, message: "添加成功", data: null};
                }else{
                    return {state: 199, message: "添加失败", data: null};
                }
            });
        next();
    }
});
//获取用户地址
router.post("/site", (req, res, next) => {
    let user = req.body.user;
    req.myPromise = query("SELECT * FROM `dt_mi_site` WHERE `user` = ?;", [user])//调用sql函数，查询符合uName的
        .then(results => {
            return {status:200,message:"",data:results};
        });
    next();
});
//获取用户某一个地址
router.post("/oneSite", (req, res, next) => {
    let id = req.body.id;
    req.myPromise = query("SELECT * FROM `dt_mi_site` WHERE `id` = ?;", [id])//调用sql函数，查询符合uName的
        .then(results => {
            return {status:200,message:"",data:results};
        });
    next();
});
//添加订单详细到数据库
router.post("/addOrderDetail", (req, res, next) => {
    let {user,time,siteId,serialNumber,product} = req.body.data;//解构传来的数据
    req.myPromise = query(
        'CALL p_get_orderDetail(?,?,?,?,?)',[ serialNumber, user , siteId, time, product, ]
    )
        .then(results => {
            console.log(results[0][0]);
            return {status:200,message:"",data:results[0][0]};
        });
    next();
});
//获取订单详情数据
router.post("/getOrderDetail",(req ,res ,next) =>{
    let orderNumber = req.body.orderNumber;
    //console.log(orderNumber);
    req.myPromise = query("SELECT * FROM `dt_mi_order_detail` WHERE `orderNumber` = ?;",[orderNumber])//调用sql函数，查询符合uName的
        .then(results => {
            return {status:200,message:"",data:results};
        });
    next();
});
//删除订单详情
router.post("/delOrderDetail",(req ,res ,next)=>{
    let id = req.body.id;//要删除的商品id
    req.myPromise = query("DELETE FROM `dt_mi_order_detail` WHERE `orderId` = ?;",[id])//获取提交过来的id
        .then(result => {
            if(result.affectedRows === 1){//返回的数据库受影响的行
                return {state:200,message:"删除成功",data:null};
            }
            else return{ state:199,message: "删除失败",data: null};
        });
    next();
});
//订单详情变成已付款
router.post("/payment",(req ,res ,next)=>{
    let id = req.body.id;//要更改的商品id
    req.myPromise = query('UPDATE `dt_mi_order_detail` SET status = ? WHERE `orderId` = ?;',[1,id])//查询数据库id相同的数据把num设置
        .then(result => {
            if(result.affectedRows === 1){//返回的数据库受影响的行
                return {state:200,message:"添加成功",data:null};
            }else{
                return {state:199,message:"添加失败",data:null};
            }
        });
    next();
});
module.exports = router;
